package com.example.zzx.dovebook.base;


import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ViewModelFactory<R> extends ViewModelProvider.NewInstanceFactory {

    private R mReponsity;

    public ViewModelFactory(R reponsity) {
        this.mReponsity = reponsity;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (mReponsity == null) {
            return super.create(modelClass);
        }
        try {
            Constructor viewModelConstrutor = modelClass.getConstructor(mReponsity.getClass());
            return (T) viewModelConstrutor.newInstance(mReponsity);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }


}
